<?php


namespace app\shop\controller\admin;


use app\shop\model\user\ChatUserModel;
use app\shop\service\chat\ChatUserService;
use think\Request;
use app\shop\controller\BaseAdminController;
use app\shop\model\config\SensitiveWordModel;
use app\shop\model\config\TypeBusinessModel;
use app\shop\model\config\TypeDesignModel;
use app\shop\model\config\TypeFieldModel;
use app\shop\model\config\TypeProgramModel;
use app\shop\model\file\FileModel;
use app\shop\model\order\OrderModel;
use app\shop\model\user\UserModel;
use app\shop\service\order\OrderService;
use app\shop\service\until\FileService;
use app\shop\validate\OrderValidate;
use think\App;
use think\facade\Db;

class OrderController extends BaseAdminController
{
    public function __construct(App $app)
    {
        $this->namespace = __NAMESPACE__;
        $this->model = new OrderModel();
        $this->field = 'id,mobile,order_sn,order_name,design_id,sale_id,design_type,delivery_time,order_status,create_time,
        due_in_refund,due_is_refund,is_take,is_open,order_amount,due_in_amount,invoice_amount,refund_amount,residue_amount,
        finalize_time,refund_time,user_id';
        $this->withModel = ['design', 'sales', 'designType'];
        $this->search = $this->getSearch($app->request);
        parent::__construct($app);
    }

    function getSearch(Request $request)
    {
        $where = [];
        $orderType = $request->param('order_type');
        if ($orderType) {
            if ($orderType == 2) {
                $where[] = ['is_complaint', '=', 1];
            }
            if ($orderType == 3) {
                $where[] = ['is_urgent', '=', 1];
            }
        }
        $designName = $request->param('design_name', '', 'trim');
        if ($designName) {
            $designId = UserModel::where('realname', 'like', "%{$designName}%")->value('user_id');
            $where[] = ['design_id', '=', $designId];
        }
        $complaint = $request->param('complaint_content', 0, 'int');
        if ($complaint) {
            $where[] = ['is_complaint', 'in', [1, 2]];
        }

        $weikuan = $request->param('residue_amount', 0, 'int');
        if ($weikuan) {
            $where[] = ['is_take', '=', 1];
        }
        $isRefund = $request->param('is_refund', '', 'trim');
        if ($isRefund === "0") {
            $where[] = ['is_refund', '=', 0];
            $where[] = ['order_status', '=', 5];
        }
        if ($isRefund == 1) {
            $where[] = ['is_refund', '=', 1];
        }
        // 定稿时间
        $finalizeTimeStart = $request->param('finalize_time_start', '', 'trim');
        if ($finalizeTimeStart) {
            $where[] = ['finalize_time', '>=', strtotime($finalizeTimeStart)];
        }
        $finalizeTimeEnd = $request->param('finalize_time_end', '', 'trim');
        if ($finalizeTimeEnd) {
            $where[] = ['finalize_time', '<', strtotime($finalizeTimeEnd) + 86400];
        }
        // 退款时间
        $refundTimeStart = $request->param('refund_time_start', '', 'trim');
        if ($refundTimeStart) {
            $where[] = ['refund_time', '>=', strtotime($refundTimeStart)];
        }
        $refundTimeEnd = $request->param('refund_time_end', '', 'trim');
        if ($refundTimeEnd) {
            $where[] = ['refund_time', '<', strtotime($refundTimeEnd) + 86400];
        }
        // 下单时间
        $createTimeStart = $request->param('create_time_start', '', 'trim');
        if ($createTimeStart) {
            $where[] = ['create_time', '>=', strtotime($createTimeStart)];
        }
        $createTimeEnd = $request->param('create_time_end', '', 'trim');
        if ($createTimeEnd) {
            $where[] = ['create_time', '<', strtotime($createTimeEnd) + 86400];
        }
        return [
            '=' => ['is_open', 'due_is_refund', 'order_status'],
            'like' => ['order_sn', 'order_name', 'mobile'],
            'custom' => $where,
        ];
    }

    /**
     * 订单列表
     * @return \think\Paginator|\think\response\Json
     */
    public function getList()
    {
        try {
            $list = parent::getList()->each(function ($item) {
                $item['order_status_txt'] = OrderModel::getOrderTxt($item['order_status']);
                return $item;
            });
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 订单详情
     * @return array|\think\response\Json
     */
    public function getOrderInfo()
    {
        try {
            $id = $this->request->param('id', 0, 'int');
            $info = OrderModel::find($id);
            if (!$info) {
                throw new \Exception('订单不存在');
            }
            $info['design_type_name'] = TypeDesignModel::where('id', $info['design_type'])->value('name', '');
            $info['business_type_name'] = TypeBusinessModel::where('id', $info['business_type'])->value('name', '');
            $info['program_name'] = TypeProgramModel::where('id', $info['program_id'])->value('name', '');
            $info['order_status_txt'] = OrderModel::getOrderTxt($info['order_status']);
            $info['design_name'] = UserModel::where('user_id', $info['design_id'])->value('realname', '');
            $info['sale_name'] = UserModel::where('user_id', $info['sale_id'])->value('realname', '');
            $info['design_need_file_arr'] = FileService::getFileArr($info['design_need_file']);
            $info['replenish_need_file_arr'] = FileService::getFileArr($info['replenish_need_file']);
            $info['remark_file_id_arr'] = FileService::getFileArr($info['remark_file_id']);
            $info['invoice_img'] = FileService::getFullUrl($info['invoice_img']);
            $info['due_refund_voucher'] = FileService::getFullUrl($info['due_refund_voucher']);
            $info['refund_voucher'] = FileService::getFullUrl($info['refund_voucher']);
            $info['create_time'] = strtotime($info['update_time']);
            return $this->success($info);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 添加订单
     * @param array $extend
     * @return \think\response\Json
     */
    public function save(array $extend = [])
    {
        Db::startTrans();
        try {
            $data = $this->request->except(['create_time', 'update_time']);
            if (isset($data['id']) && $data['id']) {
                parent::save($data);
            } else {
                $data['create_uid'] = $this->request->middleware('userId');
                OrderService::createOrder($data);
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function del()
    {
        try {
            $id = $this->request->param('id', 0);
            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            $orderInfo->delete();

            // 解散群聊
            $chatUserService = new ChatUserService();
            $chatSign = ChatUserModel::where('order_id', $id)->value('chat_sign');
            if ($chatSign) {
                $chatUserService->dissolveGroup($chatSign);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取订单状态
     * @return \think\response\Json
     */
    public function getOrderStatusArr()
    {
        try {
            $list = OrderModel::getOrderStatusArr();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取订单备选字段
     * @return \think\response\Json
     */
    public function getOrderFieldArr()
    {
        try {
            $list = TypeFieldModel::where('name', '<>', '')->select()->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 修改订单状态
     * @return \think\response\Json
     */
    public function changeOrderStatus()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            $status = $this->request->param('order_status');

            OrderService::setOrderStatus($id, $status);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 暂停订单
     * @return \think\response\Json
     */
    public function stopOrder()
    {
        try {
            $id = $this->request->param('id');

            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($orderInfo['order_status'] != 1) {
                throw new \Exception('进行中订单才可以暂停');
            }
            $orderInfo->order_status = OrderModel::STOP_ORDER;
            $orderInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 开始订单
     * @return \think\response\Json
     */
    public function startOrder()
    {
        try {
            $id = $this->request->param('id');

            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            $orderInfo->order_status = OrderModel::UNDERWAY;
            $orderInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 订单指派
     * @return \think\response\Json
     */
    public function assignOrder()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            $saleId = $this->request->param('sale_id');
            $designId = $this->request->param('design_id');
            $orderName = $this->request->param('order_name', '', 'trim');
            $userInfo = $this->request->middleware('userInfo');
            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($saleId && $saleId !== $orderInfo['sale_id']) {
                OrderService::assignSalesman($id, $saleId);
            }

            if ($designId && $designId !== $orderInfo['design_id']) {
                OrderService::assignDesigner($userInfo, $id, $designId, $orderName);
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取创建订单时的选项
     * @return \think\response\Json
     */
    public function getCreateOrderOptionArr()
    {
        try {
            $arr = OrderService::getCreateOrderOptionArr();
            return $this->success($arr);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 上传凭证
     * @return \think\response\Json
     */
    public function uploadVoucher()
    {
        try {
            $id = $this->request->param('id');
            if ($id <= 0) {
                throw new \Exception('缺少参数');
            }
            $file = $this->request->param('file');
            if (!$file) {
                throw new \Exception('请选择上传文件');
            }
            // 0退款  1待收款  2发票
            $type = $this->request->param('type');

            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($type == 0) {
                $orderInfo->order_status = 6;
                $orderInfo->is_refund = 1;
                $orderInfo->refund_time = time();
                $orderInfo->refund_voucher = $file;
            }
            if ($type == 1) {
                $orderInfo->due_is_refund = 1;
                $orderInfo->due_refund_time = time();
                $orderInfo->due_refund_voucher = $file;
                $orderInfo->due_in_refund = 1;
                $orderInfo->refund_amount = $orderInfo['due_in_amount'];
                $orderInfo->due_in_amount = 0;
            }
            if ($type == 2) {
                $orderInfo->is_open = 1;
                $orderInfo->invoice_time = time();
                $orderInfo->invoice_img = $file;
            }
            $orderInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 已收尾款
     * @return \think\response\Json
     */
    public function collection()
    {
        try {
            $id = $this->request->param('id');


            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            $orderInfo->is_take = 1;
            $orderInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}